package com.rfid.a252robot.widget;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class EditParentLayout extends LinearLayout {

    List<EditText> mEditTexts = new ArrayList<>();
    public EditParentLayout(Context context) {
        super(context);
    }

    public EditParentLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void input(String v) {
        for (int i=0;i<mEditTexts.size();i++) {
            EditText editText = mEditTexts.get(i);
            if (editText.isFocused()) {
                editText.setText("");
                editText.append(v);
                if (i < mEditTexts.size() - 1) {
                    mEditTexts.get(i + 1).requestFocus();
                }
                break;
            }
        }
    }

    public void delete() {
        for (int i=0;i<mEditTexts.size();i++) {
            EditText editText = mEditTexts.get(i);
            if (editText.isFocused()) {
                editText.setText("");
                if (i > 0) {
                    mEditTexts.get(i - 1).requestFocus();
                }
                break;
            }
        }
    }

    public String getInputKeys() {
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<mEditTexts.size();i++) {
            EditText editText = mEditTexts.get(i);
            sb.append(editText.getText().toString());
        }
        return sb.toString();
    }


    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        mEditTexts.clear();
        int count = getChildCount();
        for (int i=0;i<count;i++) {
            View v = getChildAt(i);
            if (v instanceof EditText) {
                ((EditText) v).setShowSoftInputOnFocus(false);
                mEditTexts.add((EditText) v);
            }
        }
        if (mEditTexts.size() > 0) {
            mEditTexts.get(0).requestFocus();
        }
        System.out.println("mEditTexts size = " + mEditTexts.size());
    }

}
